// pages/user-time-report/user-time-report.js
const app = getApp()

Page({
  data: {
    taskId: '',
    taskInfo: null,
    quantity: '',
    workHours: '',
    startTime: '',
    endTime: '',
    workDate: '',
    remark: '',
    productItems: [],
    images: [],
    submitting: false,
    loading: true
  },

  onLoad(options) {
    if (options.id) {
      this.setData({
        taskId: options.id
      })
      this.loadTaskInfo(options.id)
    }
    
    // 设置默认工作日期为今天
    const today = new Date()
    const year = today.getFullYear()
    const month = String(today.getMonth() + 1).padStart(2, '0')
    const day = String(today.getDate()).padStart(2, '0')
    this.setData({
      workDate: `${year}-${month}-${day}`
    })
  },

  // 加载任务信息
  loadTaskInfo(taskId) {
    app.userRequest({
      url: `/getTimeTaskDetail?task_id=${taskId}`
    }).then((res) => {
      this.setData({
        taskInfo: res.data,
        loading: false
      })
    }).catch((err) => {
      console.error('获取时间任务信息失败:', err)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: '获取任务信息失败',
        icon: 'none'
      })
    })
  },

  // 数量输入
  onQuantityInput(e) {
    const quantity = parseInt(e.detail.value) || 0
    this.setData({ quantity })
    
    if (quantity > 0) {
      this.generateProductItems(quantity)
    } else {
      this.setData({ productItems: [] })
    }
  },

  // 生成产品编号列表
  generateProductItems(quantity) {
    const productItems = []
    for (let i = 1; i <= quantity; i++) {
      const itemNo = `${this.data.taskInfo?.order_no || 'ORD'}-${String(i).padStart(3, '0')}`
      productItems.push({
        item_no: itemNo,
        images: [],
        hasImages: false
      })
    }
    this.setData({ productItems })
  },

  // 工时输入
  onWorkHoursInput(e) {
    this.setData({
      workHours: e.detail.value
    })
  },

  // 开始时间选择
  onStartTimeChange(e) {
    this.setData({
      startTime: e.detail.value
    })
    this.calculateWorkHours()
  },

  // 结束时间选择
  onEndTimeChange(e) {
    this.setData({
      endTime: e.detail.value
    })
    this.calculateWorkHours()
  },

  // 计算工作时长
  calculateWorkHours() {
    if (this.data.startTime && this.data.endTime) {
      const start = new Date(`2000-01-01 ${this.data.startTime}`)
      const end = new Date(`2000-01-01 ${this.data.endTime}`)
      const diffHours = (end - start) / (1000 * 60 * 60)
      
      if (diffHours > 0) {
        this.setData({
          workHours: diffHours.toFixed(2)
        })
      }
    }
  },

  // 工作日期选择
  onWorkDateChange(e) {
    this.setData({
      workDate: e.detail.value
    })
  },

  // 备注输入
  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  // 选择图片（产品编号）
  chooseImage(e) {
    const itemNo = e.currentTarget.dataset.itemNo
    const itemIndex = this.data.productItems.findIndex(item => item.item_no === itemNo)
    
    wx.chooseImage({
      count: 9 - this.data.productItems[itemIndex].images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.uploadImages(res.tempFilePaths, itemNo)
      }
    })
  },

  // 上传图片
  uploadImages(tempFilePaths, itemNo) {
    const itemIndex = this.data.productItems.findIndex(item => item.item_no === itemNo)
    const item = this.data.productItems[itemIndex]
    
    wx.showLoading({ title: '上传中...' })
    
    const uploadPromises = tempFilePaths.map(filePath => {
      return app.userRequest({
        url: '/uploadImage',
        method: 'POST',
        data: {
          file: filePath,
          type: 'product'
        }
      })
    })
    
    Promise.all(uploadPromises).then(results => {
      const newImages = results.map(res => res.data.url)
      const updatedImages = [...item.images, ...newImages]
      
      const productItems = [...this.data.productItems]
      productItems[itemIndex] = {
        ...item,
        images: updatedImages,
        hasImages: updatedImages.length > 0
      }
      
      this.setData({ productItems })
      wx.hideLoading()
      wx.showToast({ title: '上传成功', icon: 'success' })
    }).catch(err => {
      console.error('图片上传失败:', err)
      wx.hideLoading()
      wx.showToast({ title: '上传失败', icon: 'none' })
    })
  },

  // 删除图片（产品编号）
  deleteImage(e) {
    const { itemNo, index } = e.currentTarget.dataset
    const itemIndex = this.data.productItems.findIndex(item => item.item_no === itemNo)
    const item = this.data.productItems[itemIndex]
    
    const images = [...item.images]
    images.splice(index, 1)
    
    const productItems = [...this.data.productItems]
    productItems[itemIndex] = {
      ...item,
      images,
      hasImages: images.length > 0
    }
    
    this.setData({ productItems })
  },

  // 选择通用图片
  chooseGeneralImage() {
    wx.chooseImage({
      count: 9 - this.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.uploadGeneralImages(res.tempFilePaths)
      }
    })
  },

  // 上传通用图片
  uploadGeneralImages(tempFilePaths) {
    wx.showLoading({ title: '上传中...' })
    
    const uploadPromises = tempFilePaths.map(filePath => {
      return app.userRequest({
        url: '/uploadImage',
        method: 'POST',
        data: {
          file: filePath,
          type: 'general'
        }
      })
    })
    
    Promise.all(uploadPromises).then(results => {
      const newImages = results.map(res => res.data.url)
      this.setData({
        images: [...this.data.images, ...newImages]
      })
      
      wx.hideLoading()
      wx.showToast({ title: '上传成功', icon: 'success' })
    }).catch(err => {
      console.error('图片上传失败:', err)
      wx.hideLoading()
      wx.showToast({ title: '上传失败', icon: 'none' })
    })
  },

  // 删除通用图片
  deleteGeneralImage(e) {
    const index = e.currentTarget.dataset.index
    const images = [...this.data.images]
    images.splice(index, 1)
    this.setData({ images })
  },

  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: [url],
      current: url
    })
  },

  // 提交计时报工
  submitTimeReport() {
    // 验证必填字段
    if (!this.data.quantity || this.data.quantity <= 0) {
      wx.showToast({ title: '请输入报工数量', icon: 'none' })
      return
    }
    
    if (!this.data.workHours || this.data.workHours <= 0) {
      wx.showToast({ title: '请输入工作时长', icon: 'none' })
      return
    }
    
    if (!this.data.startTime || !this.data.endTime) {
      wx.showToast({ title: '请选择开始和结束时间', icon: 'none' })
      return
    }
    
    if (!this.data.workDate) {
      wx.showToast({ title: '请选择工作日期', icon: 'none' })
      return
    }

    this.setData({ submitting: true })

    // 准备提交数据
    const submitData = {
      task_id: this.data.taskId,
      quantity: this.data.quantity,
      work_hours: this.data.workHours,
      start_time: this.data.startTime,
      end_time: this.data.endTime,
      work_date: this.data.workDate,
      remark: this.data.remark,
      product_items: this.data.productItems.map(item => ({
        item_no: item.item_no,
        images: item.images
      })),
      images: this.data.images
    }

    app.userRequest({
      url: '/submitTimeReport',
      method: 'POST',
      data: submitData
    }).then((res) => {
      wx.showToast({
        title: '计时报工提交成功',
        icon: 'success'
      })
      
      // 返回计时任务列表页面
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }).catch((err) => {
      console.error('计时报工失败:', err)
      wx.showToast({
        title: '计时报工失败',
        icon: 'none'
      })
    }).finally(() => {
      this.setData({ submitting: false })
    })
  }
})
